package app.qrcode.browser.ykpixabay.ui.searchpic

import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import app.qrcode.browser.ykpixabay.R
import app.qrcode.browser.ykpixabay.logic.model.Hits
import app.qrcode.browser.ykpixabay.ui.star.StarViewModel
import app.qrcode.browser.ykpixabay.util.OperatePicUtil
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import kotlinx.android.synthetic.main.pic_item.view.*

/**
 * Created by YiGo on 2022/4/18.
 */
class PicAdapter(private val fragment: Fragment, private val picList: List<Hits>) :
    RecyclerView.Adapter<PicAdapter.ViewHolder>() {

    val viewModel by lazy { ViewModelProvider(fragment.requireActivity()).get(StarViewModel::class.java) }

//    private fun downloadPicByGlide(context: Context, picUrl: String) {
//        OperatePicUtil.savePicByBm(context, picUrl)
//    }

    val picViewModel by lazy {
        ViewModelProvider(
            fragment.requireActivity()
        ).get(ViewPicViewModel::class.java)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val picTag: TextView = view.findViewById(R.id.picture_tag)
        val picture: ImageView = view.findViewById(R.id.picture)
        val starbtn: ImageView = view.findViewById(R.id.star_imageView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.pic_item, parent, false)
        val holder = ViewHolder(view)

        holder.picture.setOnClickListener {
            val position = holder.absoluteAdapterPosition
            val pic = picList[position]
            val bundle = bundleOf("webformatURL" to pic.webformatURL)
            val controller = fragment.findNavController()
            controller.navigate(R.id.action_viewPicFragment_to_seePicFragment, bundle)
        }
        //长按保存图片
        holder.picture.setOnLongClickListener {
            val position = holder.absoluteAdapterPosition
            val pic = picList[position]
            AlertDialog.Builder(fragment.requireContext()).apply {
                setTitle("你要保存这张图片吗")
                setPositiveButton(
                    "确定"
                ) { _, _ ->
                    OperatePicUtil.savePicByBm(
                        context,
                        pic.webformatURL
                    )
                }
                setNegativeButton(
                    "取消"
                ) { _, _ ->

                }
            }.create().show()

            true
        }
        holder.starbtn.setOnClickListener {
            val position = holder.absoluteAdapterPosition
            val pic = picList[position]
            if (!pic.isStar) {
                viewModel.addItem(
                    newItem = Hits(
                        pic.tags,
                        pic.webformatURL,
                        pic.largeImageURL,
                        pic.id
                    )
                )
                pic.isStar = true
                notifyItemChanged(position)


            } else {
                viewModel.queryItem(pic.id)

                viewModel.singleObjectIdList.observe(fragment) { list ->
                    list.forEach {
                        viewModel.deleteOneItem(it)
                    }
                }
                pic.isStar = false
                notifyItemChanged(position)
            }
        }
        return holder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val pic = picList[position]
        if (pic.isStar) {
            holder.starbtn.setBackgroundResource(R.drawable.ic_baseline_yellow_star_24)
        } else holder.starbtn.setBackgroundResource(R.drawable.ic_baseline_star_24)
        holder.itemView.shimmerLayoutGallery.startShimmerAnimation()
        holder.itemView.shimmerLayoutText.startShimmerAnimation()
        Glide.with(holder.itemView)
            .load(pic.webformatURL)
            .listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable?,
                    model: Any?,
                    target: Target<Drawable>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false.also {
                        holder.itemView.shimmerLayoutGallery.stopShimmerAnimation()
                        holder.itemView.shimmerLayoutText.stopShimmerAnimation()
                    }
                }

            })
            .placeholder(R.drawable.ic_baseline_insert_photo_24)
            .into(holder.picture)
        holder.picTag.text = pic.tags
    }


    override fun getItemCount(): Int = picList.size
}